package org.conditure.web.http;

import java.io.IOException;

import com.google.common.base.Strings;

/**
 * Represents an HTTP response.
 * 
 * @author Elvir
 */
public class HttpResponse extends HttpPayload {
	protected String version = "HTTP/1.1";
	protected int responseCode = 200;
	protected String responseString = "OK";
	
	/**
	 * Creates an empty HTTP request.
	 */
	public HttpResponse() {
		super();
	}

	/**
	 * Loads the request header line.
	 * @throws IOException 
	 * 
	 * @see org.conditure.web.http.HttpPayload#processFirstHeaderLine(java.lang.String)
	 */
	protected void setFirstHeaderLine(String line) throws IOException {
		String[] split = line.split(" ", 3);
		
		if (split.length == 3) {
			version = split[0];
			responseCode = Integer.parseInt(split[1].trim());
			responseString = split[2].trim();
		} else {
			throw new IOException("Unable to parse first header line.");
		}
	}
	
	/**
	 * Constructs the first header line.
	 * 
	 * @see org.conditure.web.http.HttpPayload#getFirstHeaderLine(java.lang.String)
	 */
	protected String getFirstHeaderLine() {
		return String.format("%s %d %s", version, responseCode, responseString);
	}
	
	/**
	 * @return the responseCode
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * @param responseCode the responseCode to set
	 */
	public void setResponseCode(int responseCode) {
		if (responseCode < 0) {
			throw new IllegalArgumentException("Response codes cannot be less then 0");
		}
		
		this.responseCode = responseCode;
	}

	/**
	 * @return the responseString
	 */
	public String getResponseString() {
		return responseString;
	}

	/**
	 * @param responseString the responseString to set
	 */
	public void setResponseString(String responseString) {
		if (Strings.isNullOrEmpty(responseString)) {
			throw new IllegalArgumentException("Response string cannot be null or empty");
		}
		
		this.responseString = responseString;
	}

	/**
	 * @return the version
	 */
	public String getVersion() {
		return version;
	}

	/**
	 * @param version the version to set
	 */
	public void setVersion(String version) {
		if (Strings.isNullOrEmpty(version)) {
			throw new IllegalArgumentException("Version cannot be null or empty");
		}
	
		this.version = version;
	}
}
